<?php
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.modellist');
class RaovatModelRaovats extends JModelList{
public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id',
				'title'
			);
		}

		parent::__construct($config);
	}
	
	protected function populateState($ordering = null, $direction = null)
	{
		$app = JFactory::getApplication();

		// Adjust the context to support modal layouts.
		if ($layout = $app->input->get('layout'))
		{
			$this->context .= '.' . $layout;
		}

		$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
		$this->setState('filter.search', $search);
		
		$published = $this->getUserStateFromRequest($this->context . '.filter.published', 'filter_published', '');
		$this->setState('filter.published', $published);

		$categoryId = $this->getUserStateFromRequest($this->context . '.filter.category_id', 'filter_category_id');
		$this->setState('filter.category_id', $categoryId);

		// List state information.
		parent::populateState('id', 'desc');
	}
	protected function getListQuery(){
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
	
		$query->select('#__raovat.*,#__categories.title as category');
		$query->from('#__raovat');
		$query->join('INNER', '#__categories on #__raovat.category =#__categories.id');
		
		
		$search = $this->getState('filter.search');
		if($search){
			$search = $db->quote('%' . $db->escape($search, true) . '%');
			$query->where('#__raovat.title LIKE ' . $search );
		}
		$published = $this->getState('filter.published');
		if (is_numeric($published))
		{
			$query->where('#__raovat.published = ' . (int) $published);
		}
		
		$category_id = $this->getState('filter.category_id');
		if ($category_id){
			$select = "select id from #__categories WHERE parent_id= '{$category_id}'";
			
			$db->setQuery($select);
			$results = $db->loadObjectList();
			if ($results){
			 foreach ($results as $key=>$val){
			 	$temps[] = $val->id;
			 }
			 $temps = implode(',', $temps);
			 $query->where('#__raovat.category in ('.$temps.')');
			}else {
				$query->where('#__raovat.category = '.$category_id);
			}
		}
		$query->order('#__raovat.id desc');
		
		return $query;
	}
}
